<?php
   /*************************************************\
    TV-Program
    Version: 2.5
    Author: Dmitri M. Furmanoff
    E-mail: furik@mail.ru
    \*************************************************/

    /*************************************************\
    Компонент: Телепрограммы
    Версия: 2.5
    Автор: Дмитрий Фурманов
    E-mail: furik@mail.ru
    \*************************************************/
error_reporting(E_ALL ^ E_NOTICE);
defined( '_VALID_MOS' ) or die( 'Доступ к файлу запрещен.' );
global $mosConfig_absolute_path,$mosConfig_lang;

if(file_exists($mosConfig_absolute_path.'/components/com_tv/languages/'.$mosConfig_lang.'.php'))
 {
  include($mosConfig_absolute_path.'/components/com_tv/languages/'.$mosConfig_lang.'.php');
} else {
        include($mosConfig_absolute_path.'/components/com_tv/languages/russian.php');
}
require_once($mosConfig_absolute_path."/administrator/components/com_tv/class.tv.php");
require_once( $mainframe->getPath( 'admin_html' ) );

$cid = mosGetParam($_REQUEST,"cid",null);
$act = mosGetParam($_REQUEST,"act",null);
$task = mosGetParam($_REQUEST,"task",null);
$option = mosGetParam($_REQUEST,"option",null);

$pathlogo = mosGetParam($_REQUEST,"pathlogo",null);
$showanons = mosGetParam($_REQUEST,"showanons",null);
$codepage = mosGetParam($_REQUEST,"codepage",null);
$programcopy = mosGetParam($_REQUEST,"programcopy",null);
$timedelimeter = mosGetParam($_REQUEST,"timedelimeter",null);
$chandelimeter = mosGetParam($_REQUEST,"chandelimeter",null);
$weekdelimeter = mosGetParam($_REQUEST,"weekdelimeter",null);
$program_offset = mosGetParam($_REQUEST,"program_offset",null);
$componentcopy = mosGetParam($_REQUEST,"componentcopy",null);
$autoup = mosGetParam($_REQUEST,"autoup",0);
$newchan = mosGetParam($_REQUEST,"newchan",null);
$frontupdate = mosGetParam($_REQUEST,"frontupdate",null);
$filter = mosGetParam($_REQUEST,"filter",null);

$delold=mosGetParam($_REQUEST,"delold",0);
$week=mosGetParam($_REQUEST,"week",0);

switch ($act) {
  case "channels":
    $task = "showchannel";
    break;

case "upload":
    $task = "batchupload";
    break;
case "uploadanons":
    $task = "anonsupload";
    break;
case "settings":
    $task = "settings";
    break;  
}


switch ($task) {
 case "showchannel":
	showChannels( $option );
 break;

  case "publish":
	publishChannel( $cid, 1, $option );
  break;

  case "unpublish":
	publishChannel( $cid, 0, $option );
  break;

  case "publishmodule":
	publishModule( $cid, 1, $option );
  break;

  case "unpublishmodule":
	publishModule( $cid, 0, $option );
  break;

  case "import":
	importChannel( $option);
  break;

  case "new":
	editChannel( $option, 0 );
  break;

  case "edit":
	editChannel( $option, $cid[0] );
  break;

  case "remove":
	removeChannel( $cid, $option );
  break;

  case "save":
	saveChannel( $option );
  break;

  case "batchupload":
	showBatchUpload( $option );
   break;

  case "anonsupload":
	showAnonsUpload( $option );
  break;
	
 case "batchuploadhandler":
	loadProgram();
 break;

case "anonsuploadhandler":
	loadAnons();
break;

case "settings":
	showConfig( $option );
	break;
case "savesettings":
	saveConfig ($option, $pathlogo, $showanons, $codepage, $programcopy, $timedelimeter, $chandelimeter, $weekdelimeter,$program_offset, $componentcopy, $autoup, $newchan, $frontupdate,$filter);
	break;
case "orderupch":
	orderChannel( $cid[0], -1, $option );
              break;
case "orderdownch":
              orderChannel( $cid[0], 1, $option );
              break;
case "delcheck":
              delcheck( $option );
              break;

    default:
    showChannels( $option );
    break;
}

/****** Загрузка пргорамм *****/
function loadProgram()
{
global $mosConfig_absolute_path, $database;
global $week, $delold;
require_once($mosConfig_absolute_path."/administrator/components/com_tv/sub_update.php");

ignore_user_abort(TRUE); 
@ini_set("max_execution_time","600");

  $dir=$mosConfig_absolute_path."/administrator/components/com_tv/program/";
	if (file_exists($mosConfig_absolute_path."/administrator/classes/pclzip.lib.php")) {
                        require_once($mosConfig_absolute_path."/administrator/classes/pclzip.lib.php"); 
               }
    else {
	require_once($mosConfig_absolute_path."/administrator/includes/pcl/pclzip.lib.php");
           }
$file=$_FILES['zippack'];
$zipfile = new PclZip($file[tmp_name]);
	$ziplist = $zipfile->listContent();
              $zipfile->extract($p_path=$dir);

GetProgram($dir,$week,$delold, true);

$row = new mosTVChannels( $database ); 
mosMakeHtmlSafe($row->channelid);
if (!$row->check()) {
                echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
                exit();
        }
$row->checkin();
$row->updateOrder( "" );

}



/****загрузка анонсов *****/
function loadAnons(){
	global $database,$mosConfig_absolute_path,$mosConfig_offset,$week,$delold;
require_once($mosConfig_absolute_path."/administrator/components/com_tv/config.tv.php");
$dir=$mosConfig_absolute_path."/administrator/components/com_tv/program/";
	if (file_exists($mosConfig_absolute_path."/administrator/classes/pclzip.lib.php")) {
                        require_once($mosConfig_absolute_path."/administrator/classes/pclzip.lib.php"); 
               }
    else {
	require_once($mosConfig_absolute_path."/administrator/includes/pcl/pclzip.lib.php");
           }
$file=$_FILES['zippack'];
$zipfile = new PclZip($file[tmp_name]);
$ziplist = $zipfile->listContent();
$zipfile->extract($p_path=$dir);
$today=time()+($mosConfig_offset*3600);
$today=getdate($today);
$dayofweek = $today['wday']; 
$dayofweek=$dayofweek?$dayofweek:7;
$ds=1;
$wd=0;

if($delold==1)
{
$database->setQuery( "DELETE FROM #__tvanons");
		if (!$database->query()) {
    		echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
                            exit();
		}

}
$anons_count=0;
$channel_count=0;
$week=intval($week);
$anons=0;
$aname="";
$tm="";
 if (is_dir($dir)) {
   if ($dh = opendir($dir)) {
       while (($file = readdir($dh)) != false) {
        if(filetype($dir . $file)=='file' && ($file!='.' || $file!='..')){
          if(($ff=fopen($dir.$file,'r'))==true)
          {
           while(!feof($ff)){
           $str=fgets($ff,1024);
           $str=convert_cyr_string($str,$codepage,"w");
           $head=explode($weekdelimeter,$str,2);
           $head1=explode($chandelimeter,$head[1],3);
        
            switch(trim($head[0]))
					 {
					 case "Понедельник":
					  $wd=1;
            $ds=1;
					  break;
   				 case "Вторник":
					  $wd=2;
            $ds=1;
					  break;
 					 case "Среда":
					  $wd=3;
            $ds=1;
					  break;
					 case "Четверг":
					  $wd=4;
            $ds=1;
					  break;
					 case "Пятница":
					  $wd=5;
            $ds=1;
					  break;
					 case "Суббота":
					  $wd=6;
					  $ds=1;
					  break;
					 case "Воскресенье":
					  $wd=7;
					  $ds=1;
					  break;
					 default:  
            $ds=0;
           break;
					   }
					if(!$ds){ //не было смены блока
					if($cid){ 
					$str=implode($weekdelimeter,$head);
					$program=explode(" ",$str,2);

          if(preg_match("/^[0-9]{1,2}".$timedelimeter."[0-9]{1,2}/",$program[0]))
            {
              $tm=$program[0]; 
              $aname=$program[1];
              $anons="";
             }
          else
             $anons.=implode(" ",$program);

           if(trim($str)==""&&$aname!="")
            {
            $hm=explode($timedelimeter,$tm);
            $aname=htmlspecialchars($aname, ENT_QUOTES);
            $anons=htmlspecialchars($anons, ENT_QUOTES);
            $anons=str_replace("\n","<br>",$anons);
            $database->setQuery( "INSERT INTO #__tvanons (`channel`, `date`, `hour`, `minute`,`aname`, `about`) VALUES ('$cid', '".date("Y.m.d",$dat)."', '$hm[0]','$hm[1]','$aname','$anons')");
            
         		if (!$database->query()) {
    		       echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
                            exit();
		        }
		  $anons_count++;
      $tm=$program[0]; 
      $aname=$program[1];
      $anons="";      
     }

          }
          }   
          else{     // была смена блока   
              if(preg_match("/^\([\w\W]*\)/",trim($head1[1]) ))
                 {
                     $head1[1]=substr(strrchr($head1[1], ')'), 1 );  
                 }
              $head1[1]=trim($head1[1]);                                                    
              $database->setQuery( "SELECT * FROM #__tvchannels where channelname = '$head1[1]' AND published=1");
              $rows = $database->loadObjectList();
		          if(!count($rows)) //канал не найден
		                 $cid=0;        
		          else
                                            $cid=$rows[0]->cid;
               $dat=mktime(0,0,0,$today['mon'],$today['mday']-$dayofweek+$wd+$week*7,$today['year']);
               
             }
          }//файл закончился
          fclose($ff);
          unlink ($p_path="$dir$file");
       echo "Загружено:<br>";
       echo "<b>".$anons_count."</b> анонсов<br>";
       }
         }
        }
    }
}
}


function showChannels( $option ) {
  global $database,$mainframe,$mosConfig_absolute_path;
  require_once($mosConfig_absolute_path."/administrator/components/com_tv/config.tv.php");

        $limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', 10 );
        $limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );

        $limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', 10 );
        $limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );
        $search = $mainframe->getUserStateFromRequest( "search{$option}", 'search', '' );
        $search = $database->getEscaped( trim( strtolower( $search ) ) );
        
  $where = array();
    
  if ($search) {
    $where[] = "LOWER(channelname) LIKE '%$search%'";
  }

  $database->setQuery( "SELECT count(*) FROM #__tvchannels AS a".(count( $where ) ? "\nWHERE " . implode( ' AND ', $where ) : "") );
  $total = $database->loadResult();
  echo $database->getErrorMsg();
  if ($limit > $total) {
    $limitstart = 0;
  }

  $database->setQuery( "SELECT a.cid, a.channelname, a.channellogo, a.module, a.published, a.ordering, a.channelid, a.timeoffset, COUNT(b.pid) AS pcount FROM #__tvchannels a"
    ." LEFT JOIN #__tvprogramms b ON a.cid=b.channel "
    . "\nGROUP BY a.cid" 
    . (count( $where ) ? "\nHAVING " . implode( ' AND ', $where ) : "")
    . "\nORDER BY ordering" 
    . "\nLIMIT $limitstart,$limit"
  );
  $rows = $database->loadObjectList();
  if ($database->getErrorNum()) {
    echo $database->stderr();
    return false;
  }

  include_once( "includes/pageNavigation.php" );
  $pageNav = new mosPageNav( $total, $limitstart, $limit  );


  include_once( "includes/pageNavigation.php" );
  $pageNav = new mosPageNav( $total, $limitstart, $limit  );

  HTML_TVChannels::showChannels( $option, $rows, $clist, $slist, $search, $pageNav ,$pathlogo);
}

function removeChannel( $cid, $option ) {
  global $database;
  if (!is_array( $cid ) || count( $cid ) < 1) {
    echo "<script> alert('Select an item to delete'); window.history.go(-1);</script>\n";
    exit;
  }
  if (count( $cid )) {
    $cids = implode( ',', $cid );
    $database->setQuery( "DELETE FROM #__tvchannels WHERE cid IN ($cids)" );
    if (!$database->query()) {
      echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
    }
  }
  mosRedirect( "index2.php?option=$option" );
}

function publishChannel( $cid=null, $publish=1,  $option ) {
  global $database;

  if (!is_array( $cid ) || count( $cid ) < 1) {
    $action = $publish ? 'publish' : 'unpublish';
    echo "<script> alert('Выберите объект для $action'); window.history.go(-1);</script>\n";
    exit;
  }

  $cids = implode( ',', $cid );

  $database->setQuery( "UPDATE #__tvchannels SET published='$publish' WHERE cid IN ($cids)" );
  if (!$database->query()) {
    echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
    exit();
  }

  mosRedirect( "index2.php?option=$option" );
}


function publishModule( $cid=null, $module=1,  $option ) {
  global $database;

  if (!is_array( $cid ) || count( $cid ) < 1) {
    $action = $module ? 'publish' : 'unpublish';
    echo "<script> alert('Выберите объект для $action'); window.history.go(-1);</script>\n";
    exit;
  }

  $cids = implode( ',', $cid );

  $database->setQuery( "UPDATE #__tvchannels SET module='$module' WHERE cid IN ($cids)" );
  if (!$database->query()) {
    echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
    exit();
  }

  mosRedirect( "index2.php?option=$option" );
}

function importChannel($option)
{
global $mosConfig_absolute_path, $database;
require_once($mosConfig_absolute_path."/administrator/components/com_tv/sub_update.php");
$new_chan=0;
$weekname=GetKulichkiWeekName();
if($weekname)
  {
   $kulichkitv=GetKulichkiList("week=$weekname&pakets=sputnik");
   if(is_array($kulichkitv))
    {
     $Kchan=array_keys($kulichkitv);
     foreach($Kchan as $ch)
        {
          $database->setQuery( "SELECT * FROM #__tvchannels WHERE channelid='$ch'"); 
          $channels = $database->loadObjectList();
           if(!count($channels))
             {
               $database->setQuery( "INSERT INTO #__tvchannels (`channelname`,`channelid`) VALUES ('$ch','$ch')");
    	 if (!$database->query()) 
                                       {
    		            echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		            exit();
		            }
               $new_chan++; 
             }
         }
      $row = new mosTVChannels( $database ); 
      mosMakeHtmlSafe($row->channelid);
      if (!$row->check())
               {
                echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
                exit();
               }
$row->checkin();
$row->updateOrder( "" );
    }
  }
  mosRedirect( "index2.php?option=$option","Импортировано $new_chan новых каналов" );

}

function editChannel( $option, $cid ) {
  global $database, $mosConfig_absolute_path;
  require_once($mosConfig_absolute_path."/administrator/components/com_tv/config.tv.php");

  $row = new mosTVChannels( $database );

  $row->load( $cid );

  $logoFiles = mosReadDirectory( "$mosConfig_absolute_path$pathlogo" );
  $logo = array( mosHTML::makeOption( '', 'Выбрать логотип') );
  foreach ($logoFiles as $ofile) {
    if (eregi( "gif|jpg|png", $ofile )) {
      $logo[] = mosHTML::makeOption( $ofile );
    }
  }
  $logolist = mosHTML::selectList( $logo, 'channellogo', "class=\"inputbox\" size=\"1\""
  . " onchange=\"javascript:if (document.forms[0].channellogo.options[selectedIndex].value!='') {document.imagelib.src='$pathlogo/' + document.forms[0].channellogo.options[selectedIndex].value} else {document.imagelib.src='../images/M_images/blank.png'}\"",
  'value', 'text', $row->channellogo );

$orders = mosGetOrderingList( "SELECT ordering AS value, channelname AS text"
	. "\nFROM #__tvchannels"
	. "\n ORDER BY ordering"
	);
$orderlist = mosHTML::selectList( $orders, 'ordering', 'class="inputbox" size="1"',
	'value', 'text', intval( $row->ordering ) );
  if (!$cid) $row->published = 0;
  HTML_TVChannels::editChannel( $option, $row, $clist, $logolist, $pathlogo,$orderlist);
}

function saveChannel( $option ) 
{
  global $database;
  $row = new mosTVChannels( $database );
  if (!$row->bind( $_POST )) {
    echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
    exit();
  }
mosMakeHtmlSafe($row->channelid);
if (!$row->check()) {
                echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
                exit();
        }

  if (!$row->store()) {
    echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
    exit();
  }
  $row->checkin();
  $row->updateOrder( "" );
  mosRedirect( "index2.php?option=$option" );
}

function orderChannel( $cid, $inc, $option ) 
{
	global $database;
	$fp = new mosTVChannels( $database );
	$fp->load( $cid );
	$fp->move( $inc );
mosRedirect( "index2.php?option=$option&task=showchannel" );
}


function showBatchUpload( $option ) 
{
  echo "<table cellpadding='4' cellspacing='0' border='0' width='100%'><tr><td width='100%' class='sectionname'>Загрузка программ</td></tr></table>";
  echo "<form action='index2.php?task=batchuploadhandler' method='post' name='adminForm' enctype='multipart/form-data' onSubmit=\"return BatchFormCheck(this)\">";
  echo "<table width='100%' border='0' cellpadding='4' cellspacing='2' class='adminForm'>";
  echo "<tr align='center' valign='middle'><td align='center' valign='top'>";
  echo "<input type='hidden' name='option' value='$option' />";
  echo "<table border='0'>";
  echo "<tr>";
  echo "<td align='right'>Пакетный файл программ (.zip)</td><td><input type='file' name='zippack' accept='application/zip, application/x-zip-compressed'></td>";
  echo "</tr><tr>";
  echo "<td align='left'><br><input type='radio' name='week' value='0' checked />На текущую неделю </td><td align='left'><br><input type='radio' name='week' value='1' />На следующую неделю</td>";
  echo "</tr><tr>";
  echo "<td colspan='2' align='left'><br><input type='Checkbox' name='delold' value='1' checked />Очищать БД перед закачкой</td>";
  echo "</tr><tr>";
  echo "<td colspan='2' align='center'><br><input type='submit' value='Загрузить...' /></td></form>";
  echo "</tr>";
  echo "</table>";
  echo "</td></tr></table>"; 
}

function showAnonsUpload( $option ) {
  echo "<table cellpadding='4' cellspacing='0' border='0' width='100%'><tr><td width='100%' class='sectionname'>Загрузка анонсов</td></tr></table>";
  echo "<form action='index2.php?task=anonsuploadhandler' method='post' name='adminForm' enctype='multipart/form-data' onSubmit=\"return BatchFormCheck(this)\">";
  echo "<table width='100%' border='0' cellpadding='4' cellspacing='2' class='adminForm'>";
  echo "<tr align='center' valign='middle'><td align='center' valign='top'>";
  echo "<input type='hidden' name='option' value='$option' />";
  echo "<table border='0'>";
  echo "<tr>";
  echo "<td align='right'>Пакетный файл анонсов (.zip)</td><td><input type='file' name='zippack' accept='application/zip, application/x-zip-compressed'></td>";
  echo "</tr><tr>";
  echo "<td align='left'><br><input type='radio' name='week' value='0' checked />На текущую неделю </td><td align='left'><br><input type='radio' name='week' value='1' />На следующую неделю</td>";
  echo "</tr><tr>";
  echo "<td colspan='2' align='left'><br><input type='Checkbox' name='delold' value='1' checked />Очищать БД перед закачкой</td>";
  echo "</tr><tr>";
  echo "<td colspan='2' align='center'><br><input type='submit' value='Загрузить...' /></td></form>";
  echo "</tr>";
  echo "</table>";
  echo "</td></tr></table>"; 
}



function showConfig( $option ) 
{
  global $mosConfig_absolute_path;
  require($mosConfig_absolute_path."/administrator/components/com_tv/config.tv.php");
  
?>
  <form action="index2.php" method="POST" name="adminForm">
  <table cellpadding="4" cellspacing="0" border="0" width="100%" >
  <tr>
    <td width="100%" class="sectionname">
      
    </td>
  </tr>
  </table>
<script language="javascript" src="js/dhtml.js"></script>
<table cellpadding="3" cellspacing="0" border="0" width="100%">
  <tr>
    <td width="" class="tabpadding">&nbsp;</td>
    <td id="tab1" class="offtab" onclick="dhtml.cycleTab(this.id)"><?php echo _TV_ADMIN_PAGE1;?></td>
    <td id="tab2" class="offtab" onclick="dhtml.cycleTab(this.id)"><?php echo _TV_ADMIN_PAGE2;?></td>
    <td id="tab3" class="offtab" onclick="dhtml.cycleTab(this.id)"><?php echo _TV_ADMIN_PAGE3;?></td>
    <td width="90%" class="tabpadding">&nbsp;</td>
  </tr>
</table>

  <div id="page1" class="pagetext">
  <table width="100%" border="0" cellpadding="4" cellspacing="0" class="adminlist">
    <TR>
      <th  colspan="3"><div align="center"><?php echo _TV_ADMIN_CONFIG;?></div></th>
    </TR>
      <tr align="center" valign="middle">
      <td width="30%" align="left" valign="top"><strong><?php echo "Каталог логотипов:" ?></strong></td>
      <td width="20%" align="left" valign="top"><input type="text" name="pathlogo" value="<? echo "$pathlogo"; ?>" size="42"></td>
      <td width="50%" align="left" valign="top"><?php echo "Каталог, в котором будут сохраняться логотипы каналов" ?></td>
    </tr>
    <tr align="center" valign="middle">
      <td align="left" valign="top"><strong><?php echo "Включить анонсы:" ?></strong></td>
      <td align="left" valign="top">
      <?php
        $yesno[] = mosHTML::makeOption( '0', 'Нет' );
        $yesno[] = mosHTML::makeOption( '1', 'Да' );
        $yn_showanons = mosHTML::selectList( $yesno, 'showanons', 'class="inputbox"', 'value', 'text', $showanons );
        echo $yn_showanons;
      ?>
      </td>
      <td align="left" valign="top"><?php echo "Включить отображение анонсов?" ?></td>
    </tr>

<tr align="center" valign="middle">
      <td align="left" valign="top"><strong><?php echo "Разрешить обновление базы во Frontend:" ?></strong></td>
      <td align="left" valign="top">
      <?php
        $yn_frontupdate = mosHTML::selectList( $yesno, 'frontupdate', 'class="inputbox"', 'value', 'text', $frontupdate );
        echo $yn_frontupdate;
      ?>
      </td>
      <td align="left" valign="top"><?php echo "Разрешить редакторам обновлять БД из Frontend?" ?></td>
    </tr>

    <tr align="center" valign="middle">
      <td align="left" valign="top"><strong><?php echo "Добавлять новые каналы:" ?></strong></td>
      <td align="left" valign="top">
      <?php
          $yn_newchan = mosHTML::selectList( $yesno, 'newchan', 'class="inputbox"', 'value', 'text', $newchan );
        echo $yn_newchan;
      ?>
      </td>
      <td align="left" valign="top"><?php echo "Если в закачиваемой программе встречаются новые каналы, добавлять их?" ?></td>
    </tr>

    <tr align="center" valign="middle"   >
      <td align="left" valign="top"><strong><?php echo "Выделять:" ?></strong></td>
      <td align="left" valign="top"><input type="text" name="filter" value="<? echo "$filter"; ?>" size="50"></td>
      <td align="left" valign="top"><?php echo "Выделять передачи в которых встречаются указанные слова, разделённые знаком |. Например: кино|сериал" ?></td>
    </tr>

    <tr align="center" valign="middle"   >
      <td align="left" valign="top"><strong><?php echo "Копирайт программ:" ?></strong></td>
      <td align="left" valign="top"><input type="text" name="programcopy" value="<? echo "$programcopy"; ?>" size="50"></td>
      <td align="left" valign="top"><?php echo "Кем программа предоставленна?" ?></td>
    </tr>

    <tr align="center" valign="middle">
      <td align="left" valign="top"><strong><?php echo "Копирайт компонента:" ?></strong></td>
      <td align="left" valign="top">
      <?php
          $yn_componentcopy = mosHTML::selectList( $yesno, 'componentcopy', 'class="inputbox"', 'value', 'text', $componentcopy );
        echo $yn_componentcopy;
      ?>
      </td>
      <td align="left" valign="top"><?php echo "Точно, отключить?:)" ?></td>
    </tr>

 </table>

</div>
  <div id="page2" class="pagetext">
  <table width="100%" border="0" cellpadding="4" cellspacing="0" class="adminlist">
    <TR>
      <th  colspan="3"><div align="center"><?php echo _TV_ADMIN_CONFIG;?></div></th>
    </TR>
    <tr align="center" valign="middle"   >
      <td align="left" valign="top"><strong><?php echo "Кодировка программ:" ?></strong></td>
      <td align="left" valign="top"><input type="text" name="codepage" value="<? echo "$codepage"; ?>" size="21"></td>
      <td align="left" valign="top"><?php echo "В какой кодировке приходят программы? <br /> 
<b>k</b> - koi8-r <br />
<b>w</b> - windows-1251 <br />
<b>i</b> - iso8859-5 <br />
<b>a</b> - x-cp866 <br />
<b>d</b> - x-cp866 <br/>
<b>m</b>- x-mac-cyrillic 
" ?></td>
    </tr>
<tr align="center" valign="middle"   >
      <td align="left" valign="top"><strong><?php echo "Смещение времени в программе:" ?></strong></td>
      <td align="left" valign="top"><input type="text" name="program_offset" value="<? echo "$program_offset"; ?>" size="5"></td>
      <td align="left" valign="top"><?php echo "На сколько часов изменить получаемую программу" ?></td>
</tr>
<tr align="center" valign="middle"   >
      <td align="left" valign="top"><strong><?php echo "Разделитель между днем недели и датой:" ?></strong></td>
      <td align="left" valign="top"><input type="text" name="weekdelimeter" value="<? echo "$weekdelimeter"; ?>" size="5"></td>
      <td align="left" valign="top"><?php echo "Какой знак стоит после дня недели" ?></td>
</tr>
<tr align="center" valign="middle"   >
      <td align="left" valign="top"><strong><?php echo "Разделитель между датой и названием канала:" ?></strong></td>
      <td align="left" valign="top"><input type="text" name="chandelimeter" value="<? echo "$chandelimeter"; ?>" size="5"></td>
      <td align="left" valign="top"><?php echo "Какой знак стоит перед названием канала" ?></td>
</tr>


<tr align="center" valign="middle"   >
      <td align="left" valign="top"><strong><?php echo "Разделитель между часами и минутами:" ?></strong></td>
      <td align="left" valign="top"><input type="text" name="timedelimeter" value="<? echo "$timedelimeter"; ?>" size="5"></td>
      <td align="left" valign="top"><?php echo "Какой разделитель между часами и минутами в исходных данных?" ?></td>
    </tr>
    
</table>
</div>
  <div id="page3" class="pagetext">
  <table width="100%" border="0" cellpadding="4" cellspacing="0" class="adminlist">
    <TR>
      <th  colspan="3"><div align="center"><?php echo _TV_ADMIN_CONFIG;?></div></th>
    </TR>
    <tr align="center" valign="middle"   >
      <td align="left" valign="top"><strong><?php echo "Автоматически обновлять программы:" ?></strong></td>
    <td align="left" valign="top">
<?php
          $yn_autoup = mosHTML::selectList( $yesno, 'autoup', 'class="inputbox"', 'value', 'text', $autoup );
	echo $yn_autoup;
?>
  </td>
      <td align="left" valign="top"><?php echo "Включить автоматическое обновление с сайта kulicki.tv<br>Кодировкa программ должна быть - w (Windows-1251)" ?></td>
    </tr>
</table>
  </div>
<script language="javascript" type="text/javascript">dhtml.cycleTab('tab1');</script>
  

  <input type="hidden" name="option" value="<?php echo $option; ?>">
  <input type="hidden" name="task" value="">
  <input type="hidden" name="boxchecked" value="0">
</form>
<?php
}

function saveConfig ($option, $pathlogo, $showanons, $codepage, $programcopy, $timedelimeter,$chandelimeter, $weekdelimeter,$program_offset,$componentcopy,$autoup,$newchan, $frontupdate,$filter)
 {
  $configfile = "components/com_tv/config.tv.php";

  if($autoup==1)
    $codepage='w';

  @chmod ($configfile, 0766);
  $permission = is_writable($configfile);
  if (!$permission) {
    $mosmsg = "Конфигурационный файл недоступен для записи!";
    mosRedirect("index2.php?option=$option&act=config",$mosmsg);
    break;
  }
  $config = "<?php\n";
  $config .= "\$pathlogo = \"$pathlogo\";\n";
  $config .= "\$autoup = \"$autoup\";\n";
  $config .= "\$showanons = \"$showanons\";\n";
  $config .= "\$codepage = \"$codepage\";\n";
  $config .= "\$programcopy = \"$programcopy\";\n";
  $config .= "\$timedelimeter = \"$timedelimeter\";\n";
  $config .= "\$chandelimeter = \"$chandelimeter\";\n";
  $config .= "\$weekdelimeter = \"$weekdelimeter\";\n";
  $config .= "\$program_offset = \"$program_offset\";\n";
  $config .= "\$componentcopy = \"$componentcopy\";\n";
  $config .= "\$newchan = \"$newchan\";\n";
  $config .= "\$frontupdate = \"$frontupdate\";\n";
  $config .= "\$filter = \"$filter\";\n";
  $config .= "?>";

  if ($fp = fopen("$configfile", "w")) {
    fputs($fp, $config, strlen($config));
    fclose ($fp);
  @chmod ($configfile, 0711);
  }
  mosRedirect("index2.php?option=$option&task=settings", "Настройки сохранены");
}

function delcheck($option)
{
global $mosConfig_absolute_path;
$itit="0\n0\n";
  if ($fp = fopen("$mosConfig_absolute_path/administrator/components/com_tv/lastcheck.tmp", "w")) {
    fputs($fp, $init,strlen($init) );
    fclose ($fp);
    mosRedirect("index2.php?option=$option&task=channels", "Файл очищен");
 }
else
    mosRedirect("index2.php?option=$option&task=channels", "Невозможно очистить файл");   
}
?>
<br>
TV-Programm 2.5 by Dmitri M. Furmanoff













